library(colorspace)
library(foreign)
pal <- function(col, border = "light gray"){
  n <- length(col)
  plot(0, 0, type="n", xlim = c(0, 1), ylim = c(0, 1), axes = FALSE, xlab = "", ylab = "")
  rect(0:(n-1)/n, 0, 1:n/n, 1, col = col, border = NA)
}

statemaps <- function (a, grayscale=FALSE, ...){
 library (maps)
 if (length(a)==51){
   no.dc <- c(1:8,10:51)
   a <- a[no.dc]
 }
 if (length(a)==50){
   lower48 <- state.abb!="AK" & state.abb!="HI"
   a <- a[lower48]
 }
 else if (length(a)!=48){
  stop ("wrong number of states")
 }
 mapping <- list (1,2,3,4,5,6,7,9,10,11,12,13,14,15,16,17,18,19,20:22,23:24,25,26,27,28,29,30,31,32,33,34:37,38:40,41,42,43,44,45,46,47,48,49,50,51,52,53:55,56:60,61,62,63)
 # for (i in 1:length(mapping)) print(regions[mapping[[i]]])
 a.long <- rep (NA, 63)
 projection <- "bonne"
 for (i in 1:48){
   a.long[mapping[[i]]] <- a[i]
 }
  if (grayscale){
    a.long.scaled <- .95*(a.long-min(a,na.rm=TRUE))/(max(a,na.rm=TRUE)-min(a,na.rm=TRUE))
    shades <- a.long.scaled
    not.dc <- !is.na(a.long.scaled)
    shades[not.dc] <- gray (shades[not.dc])
    map('state', proj=projection, param=25, lty=0, ...)
    m <- map('state', proj=projection, param=25, fill=TRUE, plot=FALSE)
    polygon(m$x,m$y, col=shades, lwd=0.5, border="gray85")
  }
  else {
    map('state', proj=projection, param=25, lty=0, ...)
    m <- map('state', proj=projection, param=25, fill=TRUE, plot=FALSE)
    polygon(m$x,m$y, col=a.long, lwd=0.5, border="gray85")
  }
}




colorblind <- function (a, lo=min(a,na.rm=TRUE), hi=max(a,na.rm=TRUE),
                     n.shades=1001){
  a <- pmin (hi, pmax (lo, a))
  cols <-  diverge_hcl(n.shades, h = c(60, 190), c = 200, l = c(10, 90))
  #cols <- colorScale ("dark golden rod4", "light grey", "turquoise4", n.shades)
  return (cols[floor (1 + (n.shades-1)*(a-lo)/(hi-lo))])
}
